package com.funtl.my.shop.web.admin.web.controller;

import com.funtl.my.shop.domain.TbUser;
import com.funtl.my.shop.web.admin.commons.utils.CookieUtils;
import com.funtl.my.shop.web.admin.service.TbUserService;
import com.futl.my.shop.commons.constant.ConstantUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class LoginController {

    @Autowired
    private TbUserService tbUserService;

    @RequestMapping(value = {"", "login"}, method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        return "login";
    }

    /**
     * 登录
     * @param request
     * @param email
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response, String email, String password, Model model){
        TbUser user=tbUserService.login(email,password);
        if(user == null) {
            model.addAttribute("message","用户名或密码错误");
            return "login";
        }
        // 用户信息存入cookie一周
        boolean isRemember = request.getParameter("isRemember") == null ? false : true;
        if(isRemember) {
            CookieUtils.setCookie(request, response, "userInfo", String.format("%s:%s",email, password),7*24*60*60);
        }
        request.getSession().setAttribute(ConstantUtils.SESSION_USER,user);
        return "redirect:/main";
    }

    /**
     * 注销
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "login";
    }
}
